<template>
  <div class="image-uploader">
    <a-upload
      v-model:file-list="fileList"
      :multiple="true"
      :max-count="maxCount"
      :before-upload="beforeUpload"
      :custom-request="customRequest"
      :show-upload-list="true"
      list-type="picture-card"
      @preview="handlePreview"
      @remove="handleRemove"
      @change="handleChange"
    >
      <div v-if="fileList.length < maxCount">
        <plus-outlined />
        <div class="ant-upload-text">上传</div>
      </div>
    </a-upload>
    <a-modal
      v-model:open="previewVisible"
      :title="previewTitle"
      :footer="null"
      @cancel="handleCancel"
    >
      <a-image alt="预览图" style="width: 100%" :src="previewImage" />
    </a-modal>
   
  </div>
</template>

<script setup lang="ts">
import { ref, watch } from 'vue'
import { message } from 'ant-design-vue'
import { PlusOutlined } from '@ant-design/icons-vue'
import type { UploadProps, UploadFile } from 'ant-design-vue'
import { uploadImagesWithBase64 } from '@/utils/uploadImage'

// 扩展 UploadFile 类型
interface CustomUploadFile extends UploadFile {
  base64?: string
}

interface UploadedImage {
  uid: string
  url: string
  base64: string
}

const props = defineProps({
  maxCount: {
    type: Number,
    default: 5
  },
  maxSize: {
    type: Number,
    default: 5 // 默认5MB
  }
})

const emit = defineEmits(['update:modelValue', 'success', 'error'])

const fileList = ref<CustomUploadFile[]>([])
const uploadedImages = ref<UploadedImage[]>([]) // 存储所有上传成功的图片
const previewVisible = ref(false)
const previewImage = ref('')
const previewTitle = ref('')

// 上传前验证
const beforeUpload: UploadProps['beforeUpload'] = (file) => {
  // 检查文件类型
  if (!file.type.startsWith('image/')) {
    message.error('只能上传图片文件！')
    return false
  }
  
  // 检查文件大小
  if (file.size > props.maxSize * 1024 * 1024) {
    message.error(`图片大小不能超过 ${props.maxSize}MB！`)
    return false
  }
  
  return true
}

// 自定义上传
const customRequest: UploadProps['customRequest'] = async (options) => {
  const { file, onSuccess, onError, onProgress } = options
  
  try {
    const result = await uploadImagesWithBase64(
      [file as File],
      {
        maxCount: 1,
        maxSize: props.maxSize
      },
      (index: number, progress: number) => {
        onProgress?.({ percent: progress } as any)
      }
    )
    
    const response = result[0]
    // 更新文件列表
    const index = fileList.value.findIndex(item => item.uid === (file as any).uid)
    if (index !== -1) {
      fileList.value[index] = {
        ...fileList.value[index],
        status: 'done',
        url: response.response.data.file.url,
        base64: response.base64
      } as CustomUploadFile

      // 添加到上传成功图片数组
      uploadedImages.value.push({
        uid: (file as any).uid,
        // uid: response.response.data.file.id,
        url: response.response.data.file.url,
        base64: response.base64
      })
    }
    
    // 发送成功回调
    onSuccess?.(response.response)
  } catch (error) {
    console.error('上传失败:', error)
    message.error(error instanceof Error ? error.message : '上传失败')
    onError?.(error as Error)
    emit('error', error)
  }
}

// 预览图片
const handlePreview = async (file: CustomUploadFile) => {
  if (!file.response.data.file.url) {
    message.error('预览失败')
    return
  }
  
  previewImage.value = file.response.data.file.url || file.base64 || ''
  previewVisible.value = true
  previewTitle.value = file.name
}

// 取消预览
const handleCancel = () => {
  previewVisible.value = false
  previewTitle.value = ''
}

// 删除图片
const handleRemove = (file: CustomUploadFile) => {
  // 从文件列表中删除
  const index = fileList.value.findIndex(item => item.uid === file.uid)
  if (index !== -1) {
    fileList.value.splice(index, 1)
  }

  // 从上传成功图片数组中删除
  const uploadedIndex = uploadedImages.value.findIndex(item => item.uid === file.uid)
  if (uploadedIndex !== -1) {
    uploadedImages.value.splice(uploadedIndex, 1)
  }

  emit('update:modelValue', fileList.value)
}

// 上传状态改变
const handleChange: UploadProps['onChange'] = ({ fileList: newFileList }) => {
  fileList.value = newFileList as CustomUploadFile[]
  emit('update:modelValue', fileList.value)
}

// 监听fileList变化
watch(fileList, (newVal) => {
  emit('update:modelValue', newVal)
}, { deep: true })

// 监听uploadedImages变化
watch(uploadedImages, (newVal) => {
  emit('success', newVal)
}, { deep: true })
</script>

<style scoped lang="scss">
.image-uploader {
  :deep(.ant-upload-list-picture-card) {
    .ant-upload-list-item {
      padding: 0;
    }
  }
  
  :deep(.ant-upload.ant-upload-select-picture-card) {
    width: 150px;
    height: 150px;
  }
}
</style> 